use anyhow::Result;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
use toml::map::Map;
use toml::Value;

pub(crate) fn read() -> Result<Value> {
    let config_file = "config.toml";
    if !Path::new(config_file).exists() {
        let mut cfg_map = Map::new();
        let mut own_map = Map::new();
        own_map.insert("addr".into(), Value::String("0.0.0.0:9000".into()));
        cfg_map.insert("own".into(), Value::Table(own_map));

        let mut gateway_map = Map::new();
        gateway_map.insert("mock".into(), Value::Boolean(true));
        gateway_map.insert("addr".into(), Value::String("10.1.68.180:9666".into()));
        cfg_map.insert("gateway".into(), Value::Table(gateway_map));

        let mut checker_map = Map::new();
        checker_map.insert("addr".into(), Value::String("10.1.68.180:9999".into()));
        cfg_map.insert("checker".into(), Value::Table(checker_map));

        cfg_map.insert("timeout_dur".into(), Value::Integer(30));

        let mut file = File::create(config_file)?;
        let cfg = Value::Table(cfg_map);
        file.write_all(cfg.to_string().as_bytes())?;
        return Ok(cfg);
    }

    let mut file = File::open("config.toml")?;
    let mut config = String::new();
    file.read_to_string(&mut config)?;
    let cfg = toml::from_str(&*config)?;
    Ok(cfg)
}
